package com.example.zhongshuishi.taxs_api;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.dongliu.requests.RawResponse;
import net.dongliu.requests.Requests;

public class RequestKit {

	public static JSONObject request(String url, String publickey, String privatekey, String json)
			throws UnsupportedEncodingException {
		System.out.println("请求的文明:" + json);
		JSONObject requestjsonobj = JSON.parseObject(json);
		if (requestjsonobj.containsKey("input")) {
			String inputstr = requestjsonobj.getJSONObject("input").toJSONString();
			System.out.println(inputstr);
			String inputmi = AESUtil.encrypt(inputstr, privatekey);
			System.out.println("input内容加密:" + inputmi);
			requestjsonobj.put("input", inputmi);
		}

		System.out.println(requestjsonobj.toJSONString());
		String requestjson = AESUtil.encrypt(requestjsonobj.toJSONString(), publickey);
		System.out.println("报文加密:" + requestjson);
		Map<String, String> reqbody = new HashMap<String, String>();
		reqbody.put("json", URLEncoder.encode(requestjson, "UTF-8"));
		System.out.println(reqbody);
		// reqbody.put("debug", "true");
		RawResponse response = Requests.post(url).body(reqbody).verify(false).timeout(60000).send();
		String responsetext = response.readToText();
		System.out.println("接受返回报文：" + responsetext);
		JSONObject ret = JSON.parseObject(responsetext);
		String rawdata = ret.getString("data");
		if (rawdata != null && !rawdata.equals("")) {
			System.out.println(rawdata);
			String outdata = AESUtil.decrypt(rawdata, privatekey);
			System.out.println(outdata);
			Object jsonobj = JSON.parse(outdata);
			ret.put("data", jsonobj);
		}
		return ret;
	}
}
